/*
   Chiroptera - A Java client for Bacula

   The main author of Chiroptera is Marcos Paulo Serafim.
   This program is Free Software; you can redistribute it and/or
   modify it under the terms of version two of the GNU General Public
   License as published by the Free Software Foundation and included
   in the file LICENSE.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
   02110-1301, USA.
*/
package br.eti.mps.chiroptera.lib;

import br.eti.mps.chiroptera.constants.Constants;
import java.util.Hashtable;
import java.util.Map;

/**
 *
 * @author <a href="mailto:mpserafim[at]gmail[dot]com">Marcos Paulo Serafim</a>
 */
public class ConnectionFactory {

    private static Connection con;

    private ConnectionFactory() {
    }

    public static Connection getConnection() throws ChiropteraException {
        if (con == null) {
            throw new ChiropteraException(Constants.Chiroptera.Errors.NOT_CONNECTED, null, null);
        }
        return con;
    }

    public static Connection getConnection(String address, int port, String password) throws ChiropteraException {
        if (con == null) {
            Map<String, Object> configuration = new Hashtable<String, Object>();
            configuration.put(Constants.Chiroptera.ConfigurationKeys.HOST_ADDRESS, address);
            configuration.put(Constants.Chiroptera.ConfigurationKeys.HOST_PORT, port);
            configuration.put(Constants.Chiroptera.ConfigurationKeys.PASSWORD, password);
            con = new Connection(configuration);
        }
        return con;
    }

    @Override
    protected void finalize() throws Throwable {
        if (con != null) {
            con.disconnect();
        }
        super.finalize();
    }
    
}
